﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace yule.CodeBuilder.Core
{
    public static class ViewHelper
    {

        /// <summary>
        /// 解析视图
        /// </summary>
        /// <param name="context"></param>
        /// <param name="viewData"></param>
        /// <param name="tempData"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public static string ParseView(
            ControllerContext context,
            object model = null,
            string viewName = null)
        {
            //这里去寻找解析文件 cshtml
            if (viewName == null)
            {
                viewName = context.RouteData.GetRequiredString("Action");
            }

#warning 这里建议采用缓存处理

            ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewName);

            System.IO.TextWriter writer = new System.IO.StringWriter();
            //构建视图容器
            ViewContext viewContext = new ViewContext(
                context,
                viewEngineResult.View, new ViewDataDictionary() { Model = model },
                new TempDataDictionary(), writer);

            //呈现
            viewEngineResult.View.Render(viewContext, writer);
            //释放
            viewEngineResult.ViewEngine.ReleaseView(context, viewEngineResult.View);

            //这里为分布视图产生的内容
            string text = writer.ToString();
            writer.Close();
            writer.Dispose();


            return writer.ToString();
        }

    }
}